<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <title>IM</title>
    <script type="text/javascript" src="common/layui/layui.js"></script>
    <script type="text/javascript" src="common/jquery-3.2.0.min.js"></script>
    <link href="common/layui/css/layui.css" rel="stylesheet" media="all">
</head>
<body>
  <h2>WebSocket Test</h2>
  <textarea id="command" style="width:500px;height:100px">{"command":"auth","param":{"account":123456,"password":"password"}}</textarea>

  <input type="button" id="auth" value="发送">
  <div id="output"></div>
<script type="text/javascript">
var wsUri ="ws://127.0.0.1:5000";
var output;
function init() {
    output = document.getElementById("output");
    testWebSocket();
}

function testWebSocket() {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) {
        onOpen(evt)
    };
    websocket.onclose = function(evt) {
        onClose(evt)
    };
    websocket.onmessage = function(evt) {
        onMessage(evt)
    };
    websocket.onerror = function(evt) {
        onError(evt)
    };
}

function onOpen(evt) {
    writeToScreen("连接打开");
    for (var i = 0; i < 20; i++) {
      //console.log(1);
      //doSend(Math.random());
    }
}

function onClose(evt) {
    writeToScreen("连接关闭");
}

function onMessage(evt) {
    writeToScreen('<span style="color: blue;">收到消息: '+ evt.data+'</span>');
    //websocket.close();
}

function onError(evt) {
    writeToScreen('<span style="color: red;">错误:</span> '+ evt.data);
}

function doSend(message) {
    writeToScreen("SENT: " + message);
    websocket.send(message);
}

function writeToScreen(message) {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
}

window.addEventListener("load", init, false);
$("#auth").on("click",'',function(){
  c=$("#command").val()
  console.log(c);
  doSend(c)
})
</script>

</body>
</html>
